package com.fire.core.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.naming.Context;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.util.Hashtable;

/**
 * 用户登陆认证,LDAP跨域认证，通过LDAP对用户进行更新
 * @author lm
 * @created 2018-04-10 10:16
 **/
@SuppressWarnings("ALL")
public class LdapUtil {
 private static final Logger LOGGER= LoggerFactory.getLogger(LdapUtil.class);
    public LdapUtil() {

    }
    private static final String URL = "ldap://10.12.12.64:389/";
    private static final String BASEDN ="ou=People,dc=lemon,dc=com";
    private static final String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
    private static LdapContext ctx = null;
    private static final Control[] CONN_CTLS = null;

    private static void ldapConnect(String userName, String passWord) {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
        env.put(Context.PROVIDER_URL, URL + BASEDN);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        // root
        String root ="uid="+userName+",ou=People,dc=lemon,dc=com";
        env.put(Context.SECURITY_PRINCIPAL, root);
        env.put(Context.SECURITY_CREDENTIALS, passWord);
        // 此处若不指定用户名和密码,则自动转换为匿名登录
        try {
            ctx = new InitialLdapContext(env, CONN_CTLS);

            LOGGER.debug( "---------免域验证成功-------------");
        } catch (javax.naming.AuthenticationException e) {
            LOGGER.debug("----------验证失败：" + e.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*public static void main(String[] args) {
        ldapConnect("test2","123456");

    }*/
}
